package org.jetlinks.pro.assets;

import org.apache.commons.collections4.CollectionUtils;
import org.hswebframework.web.authorization.Authentication;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 *
 * @author zhouhao
 * @see AssetsHolderProvider
 * @since 1.11
 */
class AssetsHolderHolder {

    private static final List<AssetsHolderProvider> providers = new CopyOnWriteArrayList<>();

    static void addProvider(AssetsHolderProvider provider) {
        providers.add(provider);
    }

    static Mono<AssetsHolder> current() {
        return Authentication
            .currentReactive()
            .flatMap(AssetsHolderHolder::getHolder);
    }

    static Flux<AssetsHolder> currentAll() {
        return Authentication
            .currentReactive()
            .flatMapMany(AssetsHolderHolder::getHolders);
    }

    static Mono<AssetsHolder> getHolder(Authentication authentication) {
        return getHolders(authentication)
            .collectList()
            .filter(CollectionUtils::isNotEmpty)
            .map(CompositeAssetsHolder::new);

    }

    static Flux<AssetsHolder> getHolders(Authentication authentication) {
        return Flux
            .fromIterable(providers)
            .flatMap(provider -> provider.createHolder(authentication));
    }

}
